//
//  ZJTabBarViewController.m
//  GongXinDangJian
//
//  Created by apple on 17/11/29.
//  Copyright © 2017年 apple. All rights reserved.
//

#import "ZJTabBarViewController.h"
#import "YBNotificationMessageViewController.h"
#import "YBMeetingActivityViewController.h"
#import "YBNewsViewController.h"
#import "YBSanHuiYiKeViewController.h"
#import "YBPartyFeeViewController.h"
#import "YBPhoneSchoolViewController.h"
#import "ZJNavigationController.h"
#import "StudyTabBarController.h"
#import "ZJPFViewController.h"
#import "YBAcceptMessageListModel.h"
#import "JPUSHService.h"
#import "YBMessageDetailView.h"
#import "YBNoticeBackListViewController.h"
#import "YBNewWebViewController.h"

@interface ZJTabBarViewController ()<UITabBarControllerDelegate>

@property (nonatomic , strong) NSMutableArray * titleArray;

@property (nonatomic , strong) NSMutableArray * normalLogoArray;

@property (nonatomic , strong) NSMutableArray * selectLogoArray;

@property (nonatomic , strong) UIButton * currentSelectButton;

@property (nonatomic , strong) UIView * messageBadgeView;

@property (nonatomic , strong) UIView * meetingBadgeView;

@property (nonatomic , strong) UIView *bgView;
@end

@implementation ZJTabBarViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    self.titleArray = [NSMutableArray array];
    self.normalLogoArray = [NSMutableArray array];
    self.selectLogoArray = [NSMutableArray array];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadUnSignViewWithNotification:) name:@"AcceptMeetingUnSign" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadUnReadViewWithNotification:) name:@"AcceptMessageUnRead" object:nil];
    
    YBNotificationMessageViewController *messageVC = [[YBNotificationMessageViewController alloc] init];
    [self addChildVc:messageVC title:@"通知消息" image:@"tab_tzxx_d" selectedImage:@"tab_tzxx_h"];

    YBMeetingActivityViewController *meetingVC = [[YBMeetingActivityViewController alloc] init];
    [self addChildVc:meetingVC title:@"会议活动" image:@"tab_hyhd_d" selectedImage:@"tab_hyhd_h"];
    
    YBNewsViewController *newsVC = [[YBNewsViewController alloc] init];
    [self addChildVc:newsVC title:@"新闻动态" image:@"tab_xwdt_d" selectedImage:@"tab_xwdt_h"];
    
    YBSanHuiYiKeViewController *sanhuiVC = [[YBSanHuiYiKeViewController alloc] init];
    [self addChildVc:sanhuiVC title:@"三会一课" image:@"tab_shyk_d" selectedImage:@"tab_shyk_h"];
    
    YBPartyFeeViewController *dangfeiVC = [[YBPartyFeeViewController alloc] init];
    [self addChildVc:dangfeiVC  title:@"交纳党费" image:@"tab_dfjl_d" selectedImage:@"tab_dfjl_h"];
    
    YBPhoneSchoolViewController *schoolVC = [[YBPhoneSchoolViewController alloc] init];
    [self addChildVc:schoolVC title:@"在线答题" image:@"tab_sjdx_d" selectedImage:@"tab_sjdx_h"];
    
    [self setupTabBar];
    [self ybInitBadgeStatus];
    [self jpush];
    [self noticeBackMessage];
}


-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    CGRect statusBarRect = [[UIApplication sharedApplication] statusBarFrame];
    if (statusBarRect.size.height == 20) {
        self.bgView.frame = CGRectMake(0, [UIScreen zj_screenHeight] - TabbarHeight, [UIScreen zj_screenWith], TabbarHeight);
    }
    else{
        self.bgView.frame = CGRectMake(0, [UIScreen zj_screenHeight] - TabbarHeight - 20, [UIScreen zj_screenWith], TabbarHeight);
    }
}


- (void)viewWillLayoutSubviews {
    CGRect statusBarRect = [[UIApplication sharedApplication] statusBarFrame];
    if (statusBarRect.size.height == 20) {
        self.bgView.frame = CGRectMake(0, [UIScreen zj_screenHeight] - TabbarHeight, [UIScreen zj_screenWith], TabbarHeight);
    }
    else{
        self.bgView.frame = CGRectMake(0, [UIScreen zj_screenHeight] - TabbarHeight - 20, [UIScreen zj_screenWith], TabbarHeight);
    }
}


-(void)noticeBackMessage{
    [YBRequestManager request_noticeBackListWithSuccessBlock:^(id object) {
        NetWorkModel *model = [NetWorkModel yy_modelWithJSON:object];
        if ([model.STATE isEqualToString:@"20000"]) {
            NSArray * tempArray = [NSArray yy_modelArrayWithClass:[YBAcceptMessageListModel class] json:object[@"BACKOUT_MSGS"]];
            NSMutableArray * dateModelArray = [NSMutableArray array];
            for (YBAcceptMessageListModel * model in tempArray) {
                model.TITLE = @"撤销通知";
                if (model.UPDATETIME.length > 19) {
                    model.UPDATETIME = [model.UPDATETIME substringToIndex:19];
                }
                [dateModelArray addObject:model];
            }
            if (dateModelArray.count == 1) {
                YBAcceptMessageListModel * model = dateModelArray[0];
                [YBRequestManager request_readNoticeBackWithMsgId:model.ID successBlock:^(id object) {
                    
                } failBlock:^(id object) {
                    
                }];
                YBMessageDetailView * detailView = [[YBMessageDetailView alloc]initNormalMessageNoRequestDetailViewWithMessageModel:model];
                detailView.frame = CGRectMake([UIScreen zj_screenWith], 0, [UIScreen zj_screenWith], [UIScreen zj_screenHeight]);
                [self.view addSubview:detailView];
                [UIView animateWithDuration:0.2f animations:^{
                    detailView.frame = CGRectMake(0, 0, [UIScreen zj_screenWith], [UIScreen zj_screenHeight]);
                } completion:^(BOOL finished) {
                    
                }];
            }
            if (dateModelArray.count > 1) {
                YBNoticeBackListViewController * vc = [[YBNoticeBackListViewController alloc]init];
                vc.dataArray = dateModelArray;
                [self.navigationController pushViewController:vc animated:YES];
            }
        }
    } failBlock:^(id object) {
        
    }];
    
    
}


- (void)jpush{
    [JPUSHService registrationIDCompletionHandler:^(int resCode, NSString *registrationID) {
        if(resCode == 0){
            NSLog(@"registrationID获取成功：%@",registrationID);
            if ([[NSUserDefaults standardUserDefaults] objectForKey:@"isLogin"]) {
                NSMutableArray *array = [NSMutableArray array];
                [array addObject:ZJUSERINFORMODEL.ORG_ACCOUNT.ID];
                NSSet *set = [[NSSet alloc]initWithArray:array];
                [self jpushSetTags:set];
            }
        }
        else{
            NSLog(@"registrationID获取失败，code：%d",resCode);
        }
    }];
    
}


- (void)jpushSetTags:(NSSet *)set{
    __weak typeof(self) weakSelf = self;
    [JPUSHService setTags:nil alias:ZJUSERINFORMODEL.ORG_ACCOUNT.ID fetchCompletionHandle:^(int iResCode, NSSet *iTags, NSString *iAlias) {
        if (iResCode != 0) {
            [weakSelf jpushSetTags:set];
        }
        else{
            [YBRequestManager request_noticeCanSendPushNotificationWithSuccessBlock:^(id object) {
                
            } failBlock:^(id object) {
                
            }];
        }
    }];
    
}


-(void)ybInitBadgeStatus{
    [YBRequestManager request_acceptMessageListWithPage:@"1" successBlock:^(id object) {
        NetWorkModel *model = [NetWorkModel yy_modelWithJSON:object];
        if ([model.STATE isEqualToString:@"20000"]) {
            NSArray *array1 = [object objectForKey:@"UN_READ_MSGS"];
            NSArray * tempArray = [[NSArray yy_modelArrayWithClass:[YBAcceptMessageListModel class] json:array1] mutableCopy] ;
            NSInteger unReadNumber = 0;
            for (YBAcceptMessageListModel * model in tempArray) {
                if ([model.STATE integerValue] == 0) {
                    unReadNumber ++;
                }
            }
            if (unReadNumber == 0) {
                self.messageBadgeView.hidden = YES;
            }
            else{
                self.messageBadgeView.hidden = NO;
            }
        }
    } failBlock:^(id object) {
    }];
    [LPRequestManager request_miitactionHyActiongetShListWithIS_ENROLL:@"0" PAGE_INDEX:@"1" successBlock:^(id object) {
        NetWorkModel *model = [NetWorkModel yy_modelWithJSON:object];
        if ([model.STATE integerValue] == 20000) {
            /**  未报名数据  */
            NSArray *array = [object objectForKey:@"W_HYS"];
            if (array.count == 0) {
                self.meetingBadgeView.hidden = YES;
            }
            else{
                self.meetingBadgeView.hidden = NO;
            }
            
        }
    } failBlock:^(id object) {

    }];
}


-(void)reloadUnSignViewWithNotification:(NSNotification *)notification{
    if ([notification.userInfo[@"number"] integerValue] == 0) {
        self.meetingBadgeView.hidden = YES;
    }
    else{
        self.meetingBadgeView.hidden = NO;
    }
}

-(void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

-(void)reloadUnReadViewWithNotification:(NSNotification *)notification{
    if ([notification.userInfo[@"number"] integerValue] == 0) {
        self.messageBadgeView.hidden = YES;
    }
    else{
        self.messageBadgeView.hidden = NO;
    }
}



- (BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController{
    if ([viewController isKindOfClass:[YBPartyFeeViewController class]]) {
        return NO;
    }
    else{
        return YES;
    }
}



- (void)setupTabBar
{
    self.tabBar.hidden = YES;
    self.bgView = [[UIView alloc] initWithFrame:CGRectMake(0, [UIScreen zj_screenHeight] - TabbarHeight, [UIScreen zj_screenWith], TabbarHeight)];
    self.bgView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.bgView];
    
    UIView * lineView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, [UIScreen zj_screenWith], 1)];
    lineView.backgroundColor = [UIColor zj_colorWithHexString:@"b7babf"];
    [self.bgView addSubview:lineView];
    
    [self.titleArray enumerateObjectsUsingBlock:^(NSString *  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        UIButton * button = [ToolClass createUpDownButtonWithFrame:CGRectMake([UIScreen zj_screenWith] / 6 * idx, 1, [UIScreen zj_screenWith] / 6, TabbarHeight - 1) text:obj textColor:[UIColor zj_colorWithR:123 G:123 B:123 Al:1] imageName:self.normalLogoArray[idx] font:12 imageSize:25 theInterval:2];
//        [button setImage:[UIImage imageNamed:self.selectLogoArray[idx]] forState:UIControlStateSelected];
//        [button setTitleColor:[UIColor themeColor] forState:UIControlStateSelected];
        [button addTarget:self action:@selector(option_tabBarButton:) forControlEvents:UIControlEventTouchUpInside];
        button.tag = 200 + idx;
        if (idx == 0) {
            [button addSubview:self.messageBadgeView];
        }
        if (idx == 1) {
            [button addSubview:self.meetingBadgeView];
        }
        if (idx == 2) {
            [self selectedButtonWithButton:button index:idx];
            self.currentSelectButton = button;
        }
        [self.bgView addSubview:button];
    }];
    
    self.selectedIndex = 2;
    
}


-(void)option_tabBarButton:(UIButton *)sender{
    NSInteger index = sender.tag - 200;
    if (index == 4) {
        if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"cmpay://"]]) {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"cmpay://AccountInfo/fetchDFZVC?SORCNL=122&MERCSIGN=t8Gk8HsGfhIDxsOiMu5fD7bRWpOU30B8"]];
        }else{
        //跳转支付
        ZJPFViewController *vc = [ZJPFViewController new];
        [[ToolClass getMainNavigationController] pushViewController:vc animated:YES];
        }
    }else if (index == 5) {
        
        YBNewWebViewController * zj = [[YBNewWebViewController alloc]init];
        zj.titleString = @"在线答题";
        zj.isHiddenNav = YES;
        NSString * str = [[NSString stringWithFormat:@"%@" , ZJUSERINFORMODEL.ORG_ACCOUNT.USER_NAME] stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
        zj.urlString = [NSString stringWithFormat:@"%@/dist/index.html#/?user_id=%@&user_name=%@" , HTMLURL,  str, ZJUSERINFORMODEL.CURRENT_USER_MODEL.ID];
        [[ToolClass getMainNavigationController] pushViewController:zj animated:YES];
    }else{
        if (![sender isEqual:self.currentSelectButton]) {
            [self deSelectedButtonWithButton:self.currentSelectButton index:(self.currentSelectButton.tag - 200)];
            self.currentSelectButton = sender;
            [self selectedButtonWithButton:sender index:index];
            self.selectedIndex = index;
        }
    }
}

-(void)selectedButtonWithButton:(UIButton *)button index:(NSInteger)index{
    [ToolClass changeButtonWithButton:button imageString:self.selectLogoArray[index] titleColor:[UIColor themeColor]];
    
}


-(void)deSelectedButtonWithButton:(UIButton *)button index:(NSInteger)index{
    [ToolClass changeButtonWithButton:button imageString:self.normalLogoArray[index] titleColor:[UIColor zj_colorWithR:123 G:123 B:123 Al:1]];
}



- (void)addChildVc:(ZJBaseViewController *)childVc title:(NSString *)title image:(NSString *)image selectedImage:(NSString *)selectedImage
{
    childVc.title = title;
    childVc.isHomePage = YES;
    [self addChildViewController:childVc];
    [self.titleArray addObject:title];
    [self.normalLogoArray addObject:image];
    [self.selectLogoArray addObject:selectedImage];
    
}


-(UIView *)messageBadgeView
{
    if (!_messageBadgeView) {
        _messageBadgeView = [[UIView alloc]initWithFrame:CGRectMake([UIScreen zj_screenWith] / 6 - 13,5 , 8, 8)];
        _messageBadgeView.clipsToBounds = YES;
        _messageBadgeView.layer.cornerRadius = 4;
        _messageBadgeView.backgroundColor = [UIColor themeColor];
        _messageBadgeView.hidden = YES;
    }
    return _messageBadgeView;
}


-(UIView *)meetingBadgeView
{
    if (!_meetingBadgeView) {
        _meetingBadgeView = [[UIView alloc]initWithFrame:CGRectMake([UIScreen zj_screenWith] / 6 - 13,5 , 8, 8)];
        _meetingBadgeView.clipsToBounds = YES;
        _meetingBadgeView.layer.cornerRadius = 4;
        _meetingBadgeView.backgroundColor = [UIColor themeColor];
        _meetingBadgeView.hidden = YES;
    }
    return _meetingBadgeView;
}


@end
